﻿using System;
using System.Collections.Generic;
using Flagwind.Services;
using Flagwind.Resources;

namespace Flagwind.Collections.Commands
{
	[CommandOption("name", typeof(string), Description = "${Text.QueueCommand.Options.Name}")]
	public class QueueCommand : CommandBase<CommandContext>
	{
		#region 成员字段

		private IQueue _queue;
		private IQueueProvider _queueProvider;

		#endregion

		#region 构造方法

		public QueueCommand() : this("Queue")
		{
		}

		public QueueCommand(string name) : base(name)
		{
		}

		#endregion

		#region 公共属性

		[ServiceDependency]
		public IQueue Queue
		{
			get
			{
				return _queue;
			}
			set
			{
				if(value == null)
				{
					throw new ArgumentNullException();
				}

				_queue = value;
			}
		}

		[ServiceDependency]
		public IQueueProvider QueueProvider
		{
			get
			{
				return _queueProvider;
			}
			set
			{
				if(value == null)
				{
					throw new ArgumentNullException();
				}

				_queueProvider = value;
			}
		}

		#endregion

		#region 执行方法

		protected override object OnExecute(CommandContext context)
		{
			var queueName = string.Empty;

			if(context.Expression.Options.TryGetValue("queue", out queueName))
			{
				var provider = this.QueueProvider;

				if(provider == null)
				{
					throw new CommandException(ResourceUtility.GetString("Text.QueueCommand.MissingQueueProvider"));
				}

				var queue = _queueProvider.GetQueue(queueName);

				if(queue == null)
				{
					throw new CommandException(ResourceUtility.GetString("Text.QueueCommand.NotFoundQueue", queueName));
				}

				_queue = queue;
			}

			if(_queue == null)
			{
				throw new CommandException(ResourceUtility.GetString("Text.CannotObtainCommandTarget", "Queue"));
			}

			//打印队列信息
			context.Output.WriteLine(ResourceUtility.GetString("Text.QueueCommand.Message", _queue.Name, _queue.Count, _queue.GetType().FullName, _queue.ToString()));

			return _queue;
		}

		#endregion
	}
}